package com.wjerp.tplus.server.application.biz;

import com.wjerp.tplus.server.common.constant.ErrorDetail;
import com.wjerp.tplus.server.common.exception.BusinessException;
import com.wjerp.tplus.server.common.model.RoleInfoResponseData;
import com.wjerp.tplus.server.common.model.RoleInfoWrapper;
import com.wjerp.tplus.server.domain.entity.sys.*;
import com.wjerp.tplus.server.domain.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lishuailei
 */
@Transactional
@Component
public class SystemManageBiz {

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private RoleService roleService;

    @Resource
    private PermissionInfoService permissionInfoService;

    @Resource
    private UserPermissionService userPermissionService;

    @Resource
    private RolePermissionRelationService rolePermissionRelationService;

    /**
     * 获取所有的角色信息
     * @return 角色信息列表
     */
    public List<RoleInfoResponseData> loadAllRole() {
        List<RoleInfo> roleInfoList = roleService.loadAllRole();
        List<RoleInfoResponseData> roleInfoResponseDataList = new ArrayList<>(roleInfoList.size());
        for (RoleInfo data: roleInfoList){
            RoleInfoResponseData roleInfoResponseData = new RoleInfoResponseData();
            BeanUtils.copyProperties(data,roleInfoResponseData);
            List<PermissionInfo> permissionInfoList = permissionInfoService.findPermissionListByRoleId(data.getId());
            roleInfoResponseData.setPermissionInfoList(permissionInfoList);
            roleInfoResponseDataList.add(roleInfoResponseData);
        }
        return roleInfoResponseDataList;
    }

    /**
     * 创建角色
     * @param roleInfoWrapper 角色信息
     * @throws BusinessException
     */
    public void createRole(RoleInfoWrapper roleInfoWrapper) throws BusinessException {
        RoleInfo dbRoleInfo= roleService.findRoleInfoByName(roleInfoWrapper.getName());
        if(dbRoleInfo!=null){
            throw new BusinessException(ErrorDetail.ROLE_EXSITING);
        }
        dbRoleInfo = new RoleInfo();
        BeanUtils.copyProperties(roleInfoWrapper,dbRoleInfo);
        dbRoleInfo.setId(null);
        dbRoleInfo.setCreatedTime(new Date());
        Boolean result = roleService.saveRoleInfo(dbRoleInfo);
        if(!result){
            throw new BusinessException(ErrorDetail.FAIL_CREATE_ROLE);
        }

        permissionInfoTransfer(dbRoleInfo.getId(),roleInfoWrapper.getPermissionIds());
    }

    /**
     * 角色与权限ID进行转换
     * @param roleId 角色ID
     * @param permissionIds 权限ID集合
     * @throws BusinessException
     */
    private void permissionInfoTransfer(Long roleId, String permissionIds) throws BusinessException {
        //分配权限
        String[] permissionIdArr=permissionIds.split(",");
        //获取权限信息
        List<PermissionInfo> permissionInfoList=findPermissionList();
        List<RolePermissionRelation> rolePermissionRelations=new ArrayList<>();
        for(String permissionId:permissionIdArr){
            if(permissionId.isEmpty()){
                continue;
            }
            List<PermissionInfo> temp=permissionInfoList.stream().filter(p->p.getId().longValue() == Long.parseLong(permissionId)).collect(Collectors.toList());
            if(temp.size()==0){
                continue;
            }
            RolePermissionRelation rolePermissionRelation=new RolePermissionRelation();
            rolePermissionRelation.setRoleId(roleId);
            rolePermissionRelation.setPermissionId(temp.get(0).getId());
            rolePermissionRelations.add(rolePermissionRelation);

        }
        distributionPermission(roleId,rolePermissionRelations);
    }

    /**
     * 更新角色信息
     * @param roleInfoWrapper 角色信息
     * @throws BusinessException
     */
    public void updateRole(RoleInfoWrapper roleInfoWrapper) throws BusinessException {
        RoleInfo dbRoleInfo= roleService.findRoleInfoByName(roleInfoWrapper.getName());
        if(dbRoleInfo==null){
            throw new BusinessException(ErrorDetail.ROLE_NOT_EXSITING);
        }else if(!dbRoleInfo.getId().equals(roleInfoWrapper.getId())){
            throw new BusinessException(ErrorDetail.ROLE_EXSITING);
        }

        dbRoleInfo.setName(roleInfoWrapper.getName());
        dbRoleInfo.setDescription(roleInfoWrapper.getDescription());

        Boolean result = roleService.updateRoleInfo(dbRoleInfo);
        if(!result){
            throw new BusinessException(ErrorDetail.FAIL_CREATE_ROLE);
        }
        permissionInfoTransfer(dbRoleInfo.getId(),roleInfoWrapper.getPermissionIds());
    }

    /**
     * 删除角色
     * @param roleId 角色ID
     * @throws BusinessException
     */
    public void deleteRole(Long roleId) throws BusinessException {
        Boolean result = roleService.deleteRoleById(roleId);
        if(!result){
            throw new BusinessException(ErrorDetail.FAIL_CREATE_ROLE);
        }
    }

    /**
     * 获取权限信息列表
     * @return 权限信息列表
     */
    public List<PermissionInfo> findPermissionList() {
        List<PermissionInfo> permissionInfoList = permissionInfoService.findPermissionList();
        //查询默认配置的权限信息
        List<UserPermission> userPermissions = userPermissionService.findDefaultUserPermission();
        List<String> defaultPermissions = new ArrayList<>();
        userPermissions.stream().forEach(p->defaultPermissions.add(p.getPermission()));
        //只需要loginType为1的
        permissionInfoList = permissionInfoList.stream()
                .filter(p->p.getLoginType() !=null && p.getLoginType().equals(1) && !defaultPermissions.contains(p.getName())).collect(Collectors.toList());

        return  permissionInfoList;
    }

    /**
     * 分配全新给指定的角色
     * @param roleId 角色ID
     * @param rolePermissionRelations 角色与权限信息列表
     * @throws BusinessException
     */
    public void distributionPermission(Long roleId, List<RolePermissionRelation> rolePermissionRelations) throws BusinessException {
        //1、判断角色是否存在
        RoleInfo roleInfo= roleService.findRoleInfoById(roleId);
        if(roleInfo==null){
            throw new BusinessException(ErrorDetail.ROLE_NOT_EXSITING);
        }
        //2、删除已经存在的分配权限信息
        Boolean result= rolePermissionRelationService.deleteRolePermissionByRoleId(roleId);
        if(result){
            for(RolePermissionRelation data:rolePermissionRelations){
                data.setRoleId(roleId);
                result = rolePermissionRelationService.saveRolePermissionRelation(data);
                if(!result) {
                    throw new BusinessException(ErrorDetail.FAIL_DISTRIBUTION_PERMISSION_TO_USER);
                }
            }
        }else{
            throw new BusinessException(ErrorDetail.FAIL_DISTRIBUTION_PERMISSION_TO_USER);
        }
    }

    /**
     * 根据用户ID获取用户对应的权限信息列表
     * @param userId 用户ID
     * @return 权限信息列表
     * @throws BusinessException
     */
    public List<PermissionInfo> findPermissionListByUserId(Long userId) throws BusinessException {
        return userPermissionService.findPermissionListByUserId(userId);
    }

    /**
     * 根据用户ID获取用户对应的默认权限信息列表
     * @param userId 用户ID
     * @return 默认权限信息列表
     */
    public List<UserPermission> findBasePermissionListByUserId(Long userId) {
        //return systemDao.findDefaultUserPermission();
        //TODO
        return Collections.emptyList();
    }

    /**
     * 跟指定的用户增加权限信息
     * @param displayUserId 用户显示ID
     * @param permissionInfo 权限信息
     */
    public void addPermission(String displayUserId, PermissionInfo permissionInfo)  {
        if(permissionInfo == null){
            return;
        }
        try {
            //获取用户信息
            UserInfo userInfo = userInfoService.findUserInfoByDisplayUserId(displayUserId);
            List<PermissionInfo> permissionInfoList = findPermissionListByUserId(userInfo.getId());
            Long hasCount =  permissionInfoList.stream().filter(p->p.getName().equalsIgnoreCase(permissionInfo.getName())).count();
            if(hasCount>0){
                //表示已经存在不需要进行新增
                return;
            }else{
                UserPermission userPermission = new UserPermission();
                userPermission.setUserId(userInfo.getId());
                userPermission.setUserType(userInfo.getUserType());
                userPermission.setPermission(permissionInfo.getName());
                userPermissionService.saveUserPermission(userPermission);
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    /**
     * 给指定用户ID分配全新列表
     * @param displayUserId 用户显示ID
     * @param permissionInfoList 权限列表
     */
    public void addPermissionList(String displayUserId, List<PermissionInfo> permissionInfoList) {
        permissionInfoList.stream().forEach(p->addPermission(displayUserId,p));
    }
}
